Toriality's Blog

java_classes

created_at:

June 4, 2024 at 5:40 PM

last_updated:

July 15, 2024 at 8:11 PM

Classes

Declaring Classes

class MyClass {
    // field, constructors, and methods
}

In general, class declarations can include these components, in order:

  1. Modifiers: such as public, private and a number of others that you will encounter later. (However, note that the private modifier can only be applied to Nested Classes.)
  2. The class name with the initial letter capitalized by convention.
  3. The name of the class's parent (superclass) if any. Preceded by the keyword extends. A class can only extend one parent.
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement multiple interfaces.
  5. The class body surrounded by braces.

Declaring Member Variables

There are several kinds of variables:

  • Member variables in a class - these are called fields.
  • Variables in a method or block of code - these are called local variables.
  • Variables in method declarations - these are called parameters.

The Bicycle class uses the following lines to define fields:

public int cadence;
public int gear;
public int speed;

Field declarations are composed of three components, in order:

  1. Zero or more modifiers, such as public or private.
  2. The type of the field.
  3. The name of the field.

Access Modifiers

The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private modifiers. Other access modifiers will be discussed later.

  • public: the field is accessible from all classes.
  • private: the field is accessible only within its own class.

In the spirit of encapsulation it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us:

public class Bicycle {
    private int cadence;
    private int speed;
    private int gear;

    public int getCadence() {
        return cadence;
    }

    public int getSpeed() {
        return speed;
    }

    public int getGear() {
        return gear;
    }

    public void setCadence(int newValue) {
        cadence = newValue;
    }

    public void setSpeed(int newValue) {
        speed = newValue;
    }

    public void setGear(int newValue) {
        gear = newValue;
    }
}

Types

All variables must have a type. You can use primitive types such as int, float, boolean, etc. Or you can use reference types such as Strings and Arrays.

Variable Names

All variables, whether they are fields, local variables, or parameters, must have a name and follows the same naming conventions.

Defining Methods

public double calculateAnswer(
    double wingSpan,
    int numberOfEngines,
    double length,
    double grossTons
) {
    // do the calculation here
}

More generally, method declarations have six components, in order:

  1. Modifiers
  2. Return type, or void if the method does not return a value.
  3. Method name.
  4. Parameter list in parenthesis or an empty parenthesis if there are no parameters.
  5. An exception list - to be discussed later.
  6. The method body, surrounded by curly braces.

Naming Methods

By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc.

run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

Overloading Methods

Methods within a class can have the same name if they have different parameter lists.

public class DataArtist {
    public void draw(String s) {
        ...
    }

    public void draw(int i) {
        ...
    }

    public void draw(double d) {
        ...
    }

    public void draw(int i, double d) {
        ...
    }
}

Providing Constructors for Your Classes

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by using the new operator:

Bicycle myBike = new Bicycle(50, 12, 3);

new Bicycle(50, 12, 3) creates space in memory and initializes its fields.

It also can have other constructors, such as a no-argument constructor.

public Bicycle() {
    gear = 1;
    cadence = 0;
    speed = 0;
}

Bicycle yourBike = new Bicycle() invokes the no-argument constructor.

The Garbage Collector

The Java platform allows you to create as many objects you want (limited only by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determinate that they are no longer being used. This process is called garbage collection.

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object, all references to an object must be dropped before the object is eligible for garbage collection.

More About Classes

Ret